<?php
/**
 * 分类管理 (category的衍生定制)
 */
class CatApp extends CommonApp{
	
	/**
	 * 首页-分类列表
	 */
	function indexAct(){
		$item = My::arr2var($_GET,'item');
		if(!My::is_var($item))
			$this->ajaxReturn(404,'item有误!');
		$id = M('category')->item2id($item);
		$result = M('category')->id2submenu($id,array('hasParent'=>true,'publish'=>'all'));
		$this->assign('result',$result);
		$this->assign('parent_id',$id);
		//display
		$tpl = I('get.tpl','index');
		$this->display("Cat/{$item}/{$tpl}");
	}

	//编辑
	function modifyAct(){
		$item = My::arr2var($_GET,'item');
		if(!My::is_item($item))
            $this->ajaxReturn(404,"item值有误！");
		$id = My::arr2var($_GET,'id');
		//编辑
		if(My::is_id($id)){
			$result = My::id2detail('category',$id);
			if(!$result)
				$this->ajaxReturn(404,"数据不存在! ＜id={$id}＞");
			$this->assign("result",$result);
		}
		//父分类标题
		$this->assign("parent_cat_title",My::id2field('category',My::arr2var($_GET,'parent_id'),'title'));
		//取当前item分类下的所有子分类
        $cat_id = M('category')->item2id($item);
		$parent = M('category')->id2select($cat_id,array('level'=>1));
		$this->assign('parentList',$parent['select']);
		//display
		$tpl = I('get.tpl','modify');
		$this->display("Cat/{$item}/{$tpl}");
	}

	/**
	 * 保存 (添加/编辑)
	 */
	function saveAct(){
		//echo "<pre>";print_r($_POST);exit;
		$id = My::arr2var($_POST,'id');
		if(My::is_id($id)){//编辑
			if(My::arr2var($_POST,'title')=='') $this->ajaxReturn(300,"标题不能为空");
			$_POST['parent_id'] = intval(My::arr2var($_POST,'parent_id'));
			//params参数
			$params = My::id2field('category',$id,'params');
			$_POST['params'] = (is_array(My::arr2var($_POST,'params')) AND is_array($params))?array_merge($params,$_POST['params']):(is_array(My::arr2var($_POST,'params'))?$_POST['params']:$params);
			//插入
			$ok=DB('category')->where("`id`='{$id}'")->clear()->save($_POST);
			//返回
			if($ok) $this->ajaxReturn(200,"编辑成功!");
			else  $this->ajaxReturn(300,"编辑失败!");
		}else{
			if(My::arr2var($_POST,'title')=='') $this->ajaxReturn(300,"标题不能为空");
			$_POST['adddate'] = date("Y-m-d H:i:s");//编辑时间
			$_POST['parent_id'] = intval(My::arr2var($_POST,'parent_id'));
			//params参数
			$params = My::id2field('category',$id,'params');
			$_POST['params'] = (is_array(My::arr2var($_POST,'params')) AND is_array($params))?array_merge($params,$_POST['params']):(is_array(My::arr2var($_POST,'params'))?$_POST['params']:$params);
			//插入
			$ok=DB('category')->clear()->add($_POST);
			//返回
			if($ok) $this->ajaxReturn(200,"添加成功!");
			else  $this->ajaxReturn(300,"添加失败!");
		}
	}

}